import logging
import re
from models.models import *
from utils import common_utils
from google.appengine.ext import db

agent_oss = ['Windows', 'Linux', 'Mac OS', 'FreeBSD']
agent_browsers = ['MSIE', 'Opera', 'Chrome', 'Safari', 'Firefox']
def getUserAgentInfo(agent_str):
    os_info = 'Unknow'
    browser_info = 'Unknow'
    try:
        for agent_os in agent_oss:
            if(agent_str.index(agent_os)>0):
                os_info = agent_os
                break
        for agent_browser in agent_browsers:
            browser_re = agent_browser + '[/ ]((\d+\.)+\d+)'
            browser_mo = re.search(browser_re, agent_str)
            if(None != browser_mo):
                browser_info = browser_mo.group(0)
                break
    except Exception, msg:
        logging.debug(msg)
    return [os_info, browser_info]
    
def getClientInfo(request):
    client_info = []
    try:
        client_info.append(request.remote_addr)
        user_agent_info = getUserAgentInfo(request.headers['User-Agent'])
        client_info.append(';'.join(user_agent_info))
    except Exception, msg:
        logging.debug(msg)
    return client_info

default_session_id = '0123456789abcdef'
default_referer = ''
def log2db(request):
    try:
        resource_id = common_utils.getItemFromString(request.path, 2, '/')
        remote_ip = request.remote_addr
        user_agent_info = getUserAgentInfo(request.headers['User-Agent'])
        session_id = default_session_id
        if(request.cookies and request.cookies.has_key('sessionid')):
            session_id = request.cookies['sessionid']
        referer = default_referer
        if(request.headers.has_key('Referer')):
            referer = request.headers['Referer']
        query_str = request.query_string
        resource = Resource.all().filter('uuid=', resource_id)[0]
        client_info = ClientInfo(ip=remote_ip, browser=user_agent_info[1], os=user_agent_info[0],
            session=session_id, reference_url=referer, query=query_str)
        client_info.save()
        access_log = AccessLog(resource=resource, client_info=client_info)
        access_log.save()
    except Exception, msg:
        logging.debug(msg)
    